package ca.ubc.eece310.project;

/**
 * EECE 310 Term Project Fall 2009
 * @author Matthew Fong, Herman Lee, Scott Pearson
 */

import java.util.HashSet;
import java.util.Iterator;

public class MyPort {

	/**
	 * OVERVIEW: A data type designed to keep track open ports
	 * Rep-invariant: N/A
	 */

	private HashSet<MyPacket> packets;
	private double up, down;
	private int port;
	public static HashSet<MyPort> MyPorts = new HashSet<MyPort>();

	// CONSTRUCTOR
	public MyPort(int port) {
		/**
		 * EFFECTS: Constructs a port and initializes values. Adds this to
		 * MyPorts if it does not already exist
		 */
		if (!portExists(port))
			MyPorts.add(this);
		this.port = port;
		up = 0.0;
		down = 0.0;
		packets = new HashSet<MyPacket>();
	}

	public double getUp() {
		/**
		 * EFFECTS: Returns this port's upload traffic
		 */
		return up;
	}

	public double getDown() {
		/**
		 * EFFECTS: Returns this port's download traffic
		 */
		return down;
	}

	public int getPort() {
		/**
		 * EFFECTS: Returns this port's port
		 */
		return port;
	}

	public void setUp(double up) {
		/**
		 * MODIFIES: this.up EFFECTS: Sets this port's upload traffic to up
		 */
		this.up = up;
	}

	public void setDown(double down) {
		/**
		 * MODIFIES: this.up EFFECTS: Sets this port's download traffic to down
		 */
		this.down = down;
	}

	public HashSet<MyPacket> getPackets() {
		/**
		 * EFFECTS: Returns the packet's sent/received by this port
		 */
		return packets;
	}

	public void clearPackets() {
		/**
		 * MODIFIES: packets EFFECTS: Clears packets
		 */
		packets.clear();
	}

	public static boolean portExists(int port) {
		/**
		 * EFFECTS: Returns true if the specified port exists false if it doesn't
		 */
		Iterator<MyPort> itr = MyPorts.iterator();
		while (itr.hasNext()) {
			int portz = itr.next().getPort();
			if (portz == port) {
				return true;
			}
		}
		return false;
	}
	
	public boolean repOk() {
		/**
		 * EFFECTS: Returns true if the rep invariant holds for this
		 * 			else returns false
		 */
		return true;
	}
	
	public String toString() {
		/**
		 * EFFECTS: Returns a String representation
		 */
		return "Upload speed: " + up + "\nDownload speed: " + down;
	}
}
